`include "define.v"

module xy #(
	parameter PORT_NUM					=	5,
	parameter X_NODE_NUM					=	4,
	parameter Y_NODE_NUM					=	3,
	parameter SW_X_ADDR					=	2,
	parameter SW_Y_ADDR					=	1,
	parameter X_NODE_NUM_WIDTH			=	log2(X_NODE_NUM),
	parameter Y_NODE_NUM_WIDTH			=	log2(Y_NODE_NUM),
	parameter PORT_SEL_WIDTH			=	PORT_NUM-1//assum that no port whants to send a packet to itself!
	)
	(
	input 	[X_NODE_NUM_WIDTH-1		:0]	dest_x_node_in,
	input		[Y_NODE_NUM_WIDTH-1		:0]	dest_y_node_in,
	output	[PORT_SEL_WIDTH			:0]	port_sel_out// one extra bit will be removed by cross bar switch later
	);
	
	`LOG2
	
	
	localparam LOCAL	=		5'b00001;
	localparam EAST	=		5'b00010;	
	localparam NORTH	=		5'b00100;
	localparam WEST	=		5'b01000;
	localparam SOUTH	=		5'b10000;
	
	reg [PORT_SEL_WIDTH			:0]	port_sel_next;
	
	
	wire signed [X_NODE_NUM_WIDTH		:0] xc;//current 
	wire signed [X_NODE_NUM_WIDTH		:0] xd;//destination
	wire signed [Y_NODE_NUM_WIDTH		:0] yc;//current 
	wire signed [Y_NODE_NUM_WIDTH		:0] yd;//destination
	wire signed [X_NODE_NUM_WIDTH		:0] xdiff;
	wire signed [Y_NODE_NUM_WIDTH		:0] ydiff; 
	
	
	assign 	xc 	={1'b0, SW_X_ADDR [X_NODE_NUM_WIDTH-1		:0]};
	assign 	yc 	={1'b0, SW_Y_ADDR [Y_NODE_NUM_WIDTH-1		:0]};
	assign	xd		={1'b0, dest_x_node_in};
	assign	yd 	={1'b0, dest_y_node_in};
	assign 	xdiff	= xd-xc;
	assign	ydiff	= yd-yc;
	assign	port_sel_out= port_sel_next;
	
	always@(*)begin
			port_sel_next	= LOCAL;
			if				(xdiff	>  0)		port_sel_next	= EAST;
			else if		(xdiff	< 0)		port_sel_next	= WEST;
			else begin
				if			(ydiff	> 0)		port_sel_next	= SOUTH;
				else if 	(ydiff	< 0)		port_sel_next	= NORTH;
			end
	end
	

endmodule
